require('./argv')
var log4js = require('log4js')

const env = _args.koaEnv

log4js.configure({
  // 追加器
  appenders: {
    everything: {
      type: 'dateFile',
      filename: './logs/day',
      pattern: 'yyyy-MM-dd.log',
      alwaysIncludePattern: true,
      keepFileExt: true,
      // daysToKeep: 7
    }
  },
  // 字典
  categories: {
    default: {
      appenders: ['everything'],
      level: 'info'
    },
    prod: {
      appenders: ['everything'],
      level: 'info'
    }
  }
})
let logger = env === 'prod' ? log4js.getLogger('prod') : log4js.getLogger()

module.exports = async function (ctx, next) {
  // ctx.logger = logger
  // 放行请求，以捕捉请求内异常
  await next()
  // 记录大于200的错误
  const ctxBody = ctx.body
  if (ctxBody?.code > 200) {
    logger.error(JSON.stringify({
      url: ctx.url,
      message: ctxBody
    }))
  }
}